//
//  ContactListViewController.m
//  SSNDB
//
//  Created by nako on 9/16/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContactListViewController.h"
#import "SSNDBAppDelegate.h"
#import "Contact.h"
#import	"AddNewContactListViewController.h"

@implementation ContactListViewController

/* ------------------------------------------- */
@synthesize contactNoteViewController;
@synthesize tableViewContactList;
@synthesize arrayOfContactList;
@synthesize addButton;
@synthesize receiveData;


/* ------------------------------------------- */

#pragma mark -
#pragma mark === Table View Delegate ===
#pragma mark -

/* ------------------------------------------- */

- (void) setReceiveData:(NSString *)paramValue{
	if (paramValue != receiveData) {
		[receiveData release];
		receiveData = [paramValue copy];
	}
}
 

- (void)              tableView:(UITableView*)tableView 
 willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		if (self.tableViewContactList.editing == NO){
			[self setEditingModeNavigationBarButtons];
		}
	}
	
}

/* ------------------------------------------- */

- (void)              tableView:(UITableView*)tableView 
    didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath{
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		if (self.tableViewContactList.editing == NO){
			[self setDefaultNavigationBarButtons];
		}
	}
	
}

/* ------------------------------------------- */

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
		   editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	UITableViewCellEditingStyle result =
	UITableViewCellEditingStyleNone;
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		/* Allow the user to delete items from the table while we are
		 in the editing mode */
		result = UITableViewCellEditingStyleDelete;
	}
	
	return(result);
	
}


/* ------------------------------------------- */

#pragma mark -
#pragma mark === Table View Data Source ===
#pragma mark -

/* ------------------------------------------- */

- (void)  tableView:(UITableView *)tableView 
 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
  forRowAtIndexPath:(NSIndexPath *)indexPath{
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		
		/* Only allow deletion in the editing mode */
		if (editingStyle != UITableViewCellEditingStyleDelete){
			return;
		}
		
		/* Make sure our array contains the item that is about to
		 be deleted from the table view */
		if ([self.arrayOfContactList count] <= indexPath.row){
			return;
		}
		
		/* Get the contact that has to be deleted from the array */
		Contact *thisContactList = 
		[self.arrayOfContactList objectAtIndex:indexPath.row];
		
		// remove delegate array
		SSNDBAppDelegate *appDelegate = (SSNDBAppDelegate *)[[UIApplication sharedApplication] delegate];
		if( appDelegate.readSQL == YES){
		
			/* Attempt to delete the contact from the context */
			NSLog(@"index %d",indexPath.row);
			//[delegate.managedObjectContext deleteObject:thisPerson];
			NSLog(@"Delete Item");
			NSString *sqlFileName = @"SSNDB.sqlite";
			NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
			NSString *documentsDir = [documentPaths objectAtIndex:0];
			NSString *sqlFilePath = [documentsDir stringByAppendingPathComponent:sqlFileName];
		
			sqlite3 *database;
			sqlite3_stmt *statement;
		
			if(sqlite3_open([sqlFilePath UTF8String], &database) == SQLITE_OK) {
				NSString *deleteSSNDB = [ NSString stringWithFormat: @"delete from contact where contect_date=\"%@\"",thisContactList.Contact_date];
				const char *delete_stmt = [deleteSSNDB UTF8String];
				sqlite3_prepare_v2(database, delete_stmt,
								   -1, &statement, NULL);
				if (sqlite3_step(statement) == SQLITE_DONE) {
					NSLog(@"delete Done");
				}else {
					NSLog(@"delete Failed..");
				}
				sqlite3_finalize(statement);
				sqlite3_close(database);
			}
			[appDelegate.contacts removeObject:thisContactList];
		}
		
		[self.arrayOfContactList removeObject:thisContactList];
		
		NSArray *cellsToDelete = [NSArray arrayWithObject:indexPath];
		
		[tableView 
		 deleteRowsAtIndexPaths:cellsToDelete
		 withRowAnimation:UITableViewRowAnimationFade];
		
		//} else {
		/* An error happened here */
		//}
		//*/
	}
	
}

/* ------------------------------------------- */

- (NSInteger)tableView:(UITableView *)table 
 numberOfRowsInSection:(NSInteger)section{
	
	NSInteger result = 0;
	
	if ([table isEqual:self.tableViewContactList] == YES){
		
		if (self.arrayOfContactList != nil){
			result = [self.arrayOfContactList count];
		}
		
	}
	
	
	return(result);
	
}

/* ------------------------------------------- */

- (void) viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];
	
	/* Make sure we read the array of all the people in the
	 managed object context and reload our table with
	 the latest data. If in the Add New Person 
	 View Controller, we actually do add a person and
	 come back to this screen, our table view will refresh 
	 itself automatically this way */
	
	[self readAllContactList];
}

/* ------------------------------------------- */

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	UITableViewCell *cell = nil;
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		
		static NSString *SimpleIdentifier = @"ContactListCell";
		
		cell = 
		[tableView 
		 dequeueReusableCellWithIdentifier:SimpleIdentifier];
		UILabel *title1 = nil;
		UILabel *title2 = nil;
		/* A cell with sub title */
		if (cell == nil){
			cell = [[[UITableViewCell alloc] 
					   initWithStyle:UITableViewCellStyleSubtitle
					   reuseIdentifier:SimpleIdentifier] autorelease];
			CGRect tRect = CGRectMake(10.0f, 20.0f, 100.0f, 16.0f);
			title1 = [[UILabel alloc] initWithFrame:tRect];
			tRect = CGRectMake(120.0f, 20.0f, 320.0f, 14.0f);
			title2 = [[UILabel alloc] initWithFrame:tRect];
			title1.tag = 1;
			title2.tag = 2;
			[cell.contentView addSubview:title1];
			[cell.contentView addSubview:title2];
			[title1 release];
			[title2 release];
		}else {
			title1 = (UILabel *)[cell.contentView viewWithTag:1];
			title2 = (UILabel *)[cell.contentView viewWithTag:2];
		}

		
		if (self.arrayOfContactList != nil){
			
			Contact *thisContactList = 
			[self.arrayOfContactList objectAtIndex:indexPath.row];
			
			[title1 setText:thisContactList.Contact_date];
			//[title1 setTextAlignment:UITextAlignmentCenter];
			[title1 setFont: [UIFont fontWithName:@"Helvetica" size:16.0f]];
			[title1 setBackgroundColor:[UIColor clearColor]];
			
			[title2 setText:thisContactList.Note];
			//[title2 setTextAlignment:UITextAlignmentCenter];
			[title2 setFont: [UIFont fontWithName:@"Helvetica" size:14.0f]];
			[title2 setBackgroundColor:[UIColor clearColor]];	
			
		}
		
	}
	
	return(cell);
	
}

/* ------------------------------------------- */

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	
	NSInteger result = 0;
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		/* We only have one section */
		result = 1;
	}
	result =1;
	
	return(result);
	
}
/* ------------------------------------------- */

#pragma mark -
#pragma mark === Select Item ===
#pragma mark -

/* ------------------------------------------- */
- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
	 if ([tableView isEqual:self.tableViewContactList] == YES){
		 if (self.arrayOfContactList != nil){
			 
			 Contact *thisContact = 
			 [self.arrayOfContactList objectAtIndex:indexPath.row];
			 
			 if (self.contactNoteViewController == nil) {
				 ContactNoteViewController *viewController = [[ContactNoteViewController alloc] initWithNibName:@"ContactNoteViewController" bundle:nil];
				 self.contactNoteViewController = viewController;
				 [viewController release];
			 }
			 self.contactNoteViewController.thisContactList = thisContact;
			 //[self.contactNoteViewController.textViewNote setText:@"TEST"];
			 [self.navigationController pushViewController:self.contactNoteViewController animated:YES];
			 //NSLog(@"Select Item :%@",thisPerson.Name);
			 self.contactNoteViewController.title = [thisContact Contact_date];
			 [self.contactNoteViewController.textViewNote setText: [thisContact Note]];	
		 }
	 }

}

/* ------------------------------------------- */

#pragma mark -
#pragma mark === Instance Methods ===
#pragma mark -

/* ------------------------------------------- */

- (id)initWithNibName:(NSString *)nibNameOrNil 
               bundle:(NSBundle *)nibBundleOrNil {
	
	if ((self = [super initWithNibName:nibNameOrNil
								bundle:nibBundleOrNil])) {
		
		self.title = NSLocalizedString(@"ContactList", nil);
		/* Make sure we instantiate this array */
		NSMutableArray *newArray = [[NSMutableArray alloc] init];
		arrayOfContactList = [newArray retain];
		[newArray release];
		
	}
	
	return(self);
}

/* ------------------------------------------- */

- (BOOL) readAllContactList{
	
	BOOL result = NO;
	
	if (self.arrayOfContactList == nil){
		return(NO);
	}
	
	SSNDBAppDelegate *appDelegate = (SSNDBAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	
	NSMutableArray *contactList = [NSMutableArray array];
	contactList = [appDelegate.contacts mutableCopy]; 

	/* Make sure we could read the data */
	if (contactList != nil){
		/* Add all the persons from the array to our array */
		[self.arrayOfContactList removeAllObjects];
		for (int i = 0; i < [contactList count]; i++) {
			if([[[contactList objectAtIndex:i] SSN] isEqualToString:receiveData] == YES){
				/*
				NSLog(@"YES i=%d %@ %@ %@",i
					  ,[[contactList objectAtIndex:i] SSN]
					  ,[[contactList objectAtIndex:i] Contact_date]
					  ,[[contactList objectAtIndex:i] Note]
					  );
				*/
				 [self.arrayOfContactList addObject:[contactList objectAtIndex:i]];
			}
		}
		[self.tableViewContactList reloadData];
		result = YES;
		
	}
	
	return(result);
	
}

/* ------------------------------------------- */

- (void) performaddNewContactList:(id)paramSender{
	
	/* Just display the Add New Person View Controller */
	
	 AddNewContactListViewController *controller = 
	 [[AddNewContactListViewController alloc] 
	 initWithNibName:@"AddNewContactListViewController"
	 bundle:nil];
	 
	 controller.receiveSSN = receiveData;

	 //NSLog(@"----%@",controller.receiveSSN);
	 [self.navigationController pushViewController:controller
	 animated:YES];
	 
	 [controller release];
	 
	NSLog(@"@@@@@@@@@@@@@@@@@ New ContactList");
}

/* ------------------------------------------- */

- (void) performDoneEditing:(id)paramSender{
	
	/* Take the table view out of the editing mode and re-create
	 the default navigation bar buttons */
	
	[self.tableViewContactList setEditing:NO
								 animated:YES];
	
	[self setDefaultNavigationBarButtons];
	
}

/* ------------------------------------------- */

- (void) performEditTable:(id)paramSender{
	
	/* Take the table to the editing mode */
	[self setEditingModeNavigationBarButtons];
	
	[self.tableViewContactList setEditing:YES
								 animated:YES];
	
}
/* ------------------------------------------- */

- (void) setEditingModeNavigationBarButtons{
	
	/* In the editing mode, we just want a Done button on the
	 top left hand corder of the navigation bar to take the
	 table view out of the editing mode */
	
	[self.navigationItem setRightBarButtonItem:nil
									  animated:YES];
	
}

/* ------------------------------------------- */

- (void) setDefaultNavigationBarButtons{
	
	/* Here we set an add button (+) on the top right and
	 an edit button on the top left that will take our table
	 view into editing mode where the user can delete items from
	 the table and our managed object context */
	
	[self.navigationItem setRightBarButtonItem:self.addButton
									  animated:YES];
	
}

/* ------------------------------------------- */

- (void)viewDidLoad {
	[super viewDidLoad];
    
	UIBarButtonItem *newAddButton = 
	[[UIBarButtonItem alloc]
	 initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
	 target:self
	 action:@selector(performaddNewContactList:)];
	self.addButton = newAddButton;
	[newAddButton release];

	[self setDefaultNavigationBarButtons];
	
	self.tableViewContactList.rowHeight = 60.0f;
	
}

/* ------------------------------------------- */

- (void)viewDidUnload {
	[super viewDidUnload];
	
	/* Free up some memory space */
	
	self.tableViewContactList = nil;
	self.arrayOfContactList = nil;
	self.addButton = nil;
	
	self.navigationItem.rightBarButtonItem = nil;
	self.navigationItem.leftBarButtonItem = nil;
	
}

/* ------------------------------------------- */

- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (YES);
}

/* ------------------------------------------- */

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
}

/* ------------------------------------------- */

- (void)dealloc {
	
	[contactNoteViewController release];
	[receiveData release];
	[arrayOfContactList release];
	[tableViewContactList release];
	[addButton release];
	
	[super dealloc];
}

/* ------------------------------------------- */

@end
